package com.zh.media.ui;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.zh.media.R;
import com.zh.media.data.model.Barcode;
import com.zh.media.data.model.Barcodes;
import com.zh.media.data.model.TokenBean;
import com.zh.media.https.MqttManager;
import com.zh.media.utils.BgCount;
import com.zh.media.utils.Constants;
import com.zh.media.utils.DevClient;
import com.zh.media.utils.MacAddressUtil;
import com.zh.media.utils.ScreenController;
import com.zh.media.utils.ScreenUtil;
import com.zh.media.utils.view.CodeUtils;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description:     主界面
 * @Author:         mark
 * @CreateDate:     2024/11/5 10:28
 * @UpdateUser:     更新者：
 * @UpdateDate:     2024/11/5 10:28
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
public class MainActivity extends AppCompatActivity {

    //log
    private static final Logger logger = Logger.getLogger(MainActivity.class);

    private ImageView imageUp1,imageUp2,imageUp3,imageUp4,imageUp5,imageUp6,
            imageUp7,imageUp8,imageUp9,imageUp10;
    private ImageView imageDown1,imageDown2,imageDown3,imageDown4,imageDown5,imageDown6,
            imageDown7,imageDown8,imageDown9,imageDown10;
    private LinearLayout ly_up, ly_down;

    private List<Barcode> barcodes = new ArrayList<>();

    private OkHttpClient client = new OkHttpClient();

    private static String TAG = "MainActivity";
    private String token = "";

    //订阅主题
    private String mainTopic = "media/#";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intView();
        logger.debug("这是一个调试信息");
        logger.info("这是一个信息信息");
        logger.warn("这是一个警告信息");
        logger.error("这是一个错误信息");


        getScreenWH();
        Log.e("mqtt", "mqtt初始化");
        initMqtt();
        ScreenController screenController = new ScreenController(this);
        // 亮屏
        screenController.turnScreenOn();
        // 熄屏
        screenController.turnScreenOff();



      httpAsynchronousPost(Constants.GET_TOKEN_URL);
      //httpAsynchronousGet(Constants.LAYOUT_URL+"/MT0001");
      //
      httpAsynchronousGet(Constants.GET_CHECK_SETTING+"/vigiot!@2024");
      httpAsynchronousGet(Constants.GET_TIME+"/MT0001");
    }

    /**
     * OkHttp 异步 Get 请求
     */
    private void httpAsynchronousGet(String url) {
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .addHeader("Authorization",getUserInfo("access_token"))
                .url(url)   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();

        // 创建异步回调
        Callback callback = new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
                Log.e("getlayout", "收到消息"+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.e("getlayout", "收到消息"+result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result);
                            String msgs = jsonObject.getString("msg");
                            String dataStr = jsonObject.getString("data");
                            if (TextUtils.isEmpty(msgs) && msgs.equals("success")){
                                initData(getBarcodes(dataStr));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        };

        // 异步 Get 请求
        client.newCall(request).enqueue(callback);
    }




    /**
     * OkHttp 异步 Post 请求
     */
    private void httpAsynchronousPost(String url) {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        JSONObject josnBody = new JSONObject();
        String dataToEncrypt = "123456";

        try {
            String code = DevClient.encryptWithPublicKey(dataToEncrypt);
            josnBody.put("deviceAuthorizeCode", code);

            Log.e(TAG, "加密  "+code);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                josnBody.toString());
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url(url)   // 设置请求地址
                .post(requestBody)// 使用 Post 方法
                .build();

        // 创建异步回调
        Callback callback = new Callback(){


            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
                Log.e(TAG, "result : " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String msgs = jsonObject.getString("msg");
                    String dataStr = jsonObject.getString("data");
                    int code = jsonObject.getInt("code");
                    if (code == 0 && !TextUtils.isEmpty(dataStr)){
                        JSONObject jsb = new JSONObject(dataStr);
                        saveUserInfo(jsb.getString("access_token"),
                                jsb.getString("refresh_token"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };

        // 异步 Get 请求
        client.newCall(request).enqueue(callback);
    }

    /**
     * @description 存储token
     * @date: 2024/12/7 10:56
     * @author: mark
     * @param
     * @return
     */
    private void saveUserInfo(String access_token, String refresh_token) {
        if (TextUtils.isEmpty(access_token) || TextUtils.isEmpty(refresh_token)){
            return;
        }
        // 获取SharedPreferences对象
        SharedPreferences sharedPreferences = getSharedPreferences("MyInfo", MODE_PRIVATE);

        // 使用SharedPreferences.Editor添加数据
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("access_token", access_token);
        editor.putString("refresh_token", refresh_token);
        // 提交保存
        editor.apply();

    }

     /**
      * @description 获取键值对的值
      * @date: 2024/12/8 16:15
      * @author: mark
      * @param
      * @return
      */
    private String getUserInfo(String key) {
        // 获取SharedPreferences对象
        SharedPreferences sharedPreferences = getSharedPreferences("MyInfo", MODE_PRIVATE);
        String access = sharedPreferences.getString(key,"");
        Log.e(TAG,key+"==="+access);
       return access;
    }

    /**
     * @describetion 初始化Mqtt
     * @author mark
     * @param
     * @param
     * @return
    */
    private void initMqtt() {
        MqttManager mqtt = new MqttManager();
        mqtt.connectMqtt();
        mqtt.subscribe(mainTopic, new MqttCallback() {

            @Override
            public void connectionLost(Throwable throwable) {

            }


            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Log.e("mqtt", "收到消息"+message.toString());
                if (topic != null && topic.equals(mainTopic) && message != null){
                    String msg = message.toString();
                    logger.info(msg);
                    Log.e("mqtt", msg);
                    try {
                        JSONObject jsonObject = new JSONObject(msg);
                        String msgs = jsonObject.getString("msg");
                        String dataStr = jsonObject.getString("data");
                        if (TextUtils.isEmpty(msgs) && msgs.equals("success")){

                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }

                    Toast.makeText(MainActivity.this,"接收成功",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
    }

    // 从 Base64 编码字符串获取 PublicKey 对象
    private PublicKey getPublicKeyFromBase64(String base64PublicKey) throws Exception {
        byte[] decoded = Base64.decode(base64PublicKey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    // 使用公钥加密数据
    private byte[] encryptWithPublicKey(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

     /**
      * @description 获取鉴权私钥
      * @date: 2024/12/7 15:37
      * @author: mark
      * @param
      * @return
      */
    private String getAuthorKey(){
        String code = "";
        // 示例：公钥（Base64 编码形式）
        String publicKeyBase64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArNFjgw45e/heWyvfxGvYbZtvppFnPiD7fHPM3MQ77mTfyp7xdI/XYJY6WDd+dCHB3ry/mgvyrH3njntiJZOyAcRBJQ7/xOup2Uiw8fZltAdlDAz19BZgJlZqQNSalxmUbmKgdOSnOVRSeSckAoTWdj4Ykqp+k09hhYxYEVqmfPKjA/Mu2GT59hx8ThynDZzS5U0/tK11evuPw5cjLRLK0bGviTegZNj41yatHXmGdzjuJVODRsaYiqgENoYt4l6dmNmrWIDvpGqVsROighMHHslsQEN6eoO5AB7A+Y6JcqXMWBNChMDUGWoxqsg6gROeMkAKESInx3Qr9pg0JldIfQIDAQAB";

        try {
            // 将 Base64 编码的公钥字符串转换为 PublicKey 对象
            PublicKey publicKey = getPublicKeyFromBase64(publicKeyBase64);

            // 待加密的mac数据
            String dataToEncrypt = "123456";
           //dataToEncrypt = MacAddressUtil.getMacAddr(this);
            Log.d(TAG, "macdizhi: " + dataToEncrypt);

            // 使用公钥加密数据
            byte[] encryptedData = encryptWithPublicKey(dataToEncrypt, publicKey);

            // 将加密后的数据转换为 Base64 字符串，方便发送
            String encryptedDataBase64 = Base64.encodeToString(encryptedData, Base64.DEFAULT);

            Log.d(TAG, "Encrypted Data (Base64): " + encryptedDataBase64);

            // 发送加密数据到服务器
            //....

        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }


    private String getImage(String sn){
        String url = "";
        String command = "/usr/bin/cimage -s /var/tmp/" + sn + " -o /usr/project/image";
        //tagImageTask = appendedLog(tagImageTask, "执行json转图片指令..." + command);

        //执行命令  通过cimage 把var/tmp/下的json文件转成图片 保存到/usr/project/image/下
        ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command);
        try {
            Process process = Runtime.getRuntime().exec(command);
            // 获取命令行指令的输出信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理输出信息，例如打印到Logcat或UI
                Log.i("ExecCommand", line);
            }
            int exitCode = process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * @describetion 獲取屏幕寬高
     * @author mark
     * @param
     * @param
     * @return
    */
    private void getScreenWH() {
        Point resolutionWithStatusBar = getScreenResolutionWithStatusBar(this);
        int screenWidth = resolutionWithStatusBar.x;
        int screenHeight = resolutionWithStatusBar.y;
        //int screenWidth = ScreenUtil.getScreenWidth(this);
        //int screenHeight = ScreenUtil.getScreenHeight(this);
        //Toast.makeText(getApplicationContext(),
         //       "您已成功打开一个Toast-width="+screenWidth+" h="+screenHeight, Toast.LENGTH_SHORT).show();
    }

    /**
     * @describetion 初始化控件
     * @author mark
     * @param
     * @param
     * @return
    */
    private void intView(){
        imageUp1 = findViewById(R.id.imageUp1);
        imageUp2 = findViewById(R.id.imageUp2);
        imageUp3 = findViewById(R.id.imageUp3);
        imageUp4 = findViewById(R.id.imageUp4);
        imageUp5 = findViewById(R.id.imageUp5);
        imageUp6 = findViewById(R.id.imageUp6);
        imageUp7 = findViewById(R.id.imageUp7);
        imageUp8 = findViewById(R.id.imageUp8);
        imageUp9 = findViewById(R.id.imageUp9);
        imageUp10 = findViewById(R.id.imageUp10);
        imageDown1 = findViewById(R.id.imageDown1);
        imageDown2 = findViewById(R.id.imageDown2);
        imageDown3 = findViewById(R.id.imageDown3);
        imageDown4 = findViewById(R.id.imageDown4);
        imageDown5 = findViewById(R.id.imageDown5);
        imageDown6 = findViewById(R.id.imageDown6);
        imageDown7 = findViewById(R.id.imageDown7);
        imageDown8 = findViewById(R.id.imageDown8);
        imageDown9 = findViewById(R.id.imageDown9);
        imageDown10 = findViewById(R.id.imageDown10);

        ly_up = findViewById(R.id.codeUpLy);
        ly_down = findViewById(R.id.codeDownLy);


    }

    /**
     * @describetion 初始化數據
     * @author mark
     * @param
     * @param
     * @return
    */
    private void initData(Barcodes bs) {

        List<Barcode> bblist = new ArrayList<>();
        List<Barcode> bbUplist = new ArrayList<>();
        List<Barcode> bbDownlist = new ArrayList<>();
        int row = 0 , cols = 0;
        if (bs != null && bs.getVtags() != null){
            bblist = bs.getVtags();
            if (TextUtils.isEmpty(bs.getrOWZ()) && TextUtils.isEmpty(bs.getCols())){
                row = Integer.parseInt(bs.getrOWZ());
                cols = Integer.parseInt(bs.getCols());
            }
            if (row == 1){
                ly_down.setVisibility(View.GONE);
            }

        }

        if(bblist != null && bblist.size() > 0){
            for (int i = 0; i < bblist.size(); i++){
                if (i < cols){
                    bbUplist.add(bblist.get(i));

                }else {
                    bbDownlist.add(bblist.get(i));
                }


            }
        }

        if(bbUplist != null && bbUplist.size() > 0){
            for (int i = 0; i < bblist.size(); i++){
                Drawable drawable = getDrawable(bbUplist.get(i).getGoodsCode());
                switch (i){
                    case Constants.BG_ZERO:
                        imageUp1.setBackground(drawable);
                        imageUp1.setVisibility(View.VISIBLE);
                    case Constants.BG_ONE:
                        imageUp2.setBackground(drawable);
                        imageUp2.setVisibility(View.VISIBLE);
                    case Constants.BG_TWO:
                        imageUp3.setBackground(drawable);
                        imageUp3.setVisibility(View.VISIBLE);
                    case Constants.BG_THREE:
                        imageUp4.setBackground(drawable);
                        imageUp4.setVisibility(View.VISIBLE);
                    case Constants.BG_FOUER:
                        imageUp5.setBackground(drawable);
                        imageUp5.setVisibility(View.VISIBLE);
                    case Constants.BG_FIVE:
                        imageUp6.setBackground(drawable);
                        imageUp6.setVisibility(View.VISIBLE);
                    case Constants.BG_SIX:
                        imageUp7.setBackground(drawable);
                        imageUp7.setVisibility(View.VISIBLE);
                    case Constants.BG_SEVEN:
                        imageUp8.setBackground(drawable);
                        imageUp8.setVisibility(View.VISIBLE);
                    case Constants.BG_EIGHT:
                        imageUp9.setBackground(drawable);
                        imageUp9.setVisibility(View.VISIBLE);
                    case Constants.BG_NINE:
                        imageUp10.setBackground(drawable);
                        imageUp10.setVisibility(View.VISIBLE);
                    case Constants.BG_TEN:

                }
            }
        }

        if(bbDownlist != null && bbDownlist.size() > 0){
            for (int i = 0; i < bbDownlist.size(); i++){
                Drawable drawable = getDrawable(bbDownlist.get(i).getGoodsCode());
                switch (i){
                    case Constants.BG_ZERO:
                        imageDown1.setBackground(drawable);
                        imageDown1.setVisibility(View.VISIBLE);
                    case Constants.BG_ONE:
                        imageDown2.setBackground(drawable);
                        imageDown2.setVisibility(View.VISIBLE);
                    case Constants.BG_TWO:
                        imageDown3.setBackground(drawable);
                        imageDown3.setVisibility(View.VISIBLE);
                    case Constants.BG_THREE:
                        imageDown4.setBackground(drawable);
                        imageDown4.setVisibility(View.VISIBLE);
                    case Constants.BG_FOUER:
                        imageDown5.setBackground(drawable);
                        imageDown5.setVisibility(View.VISIBLE);
                    case Constants.BG_FIVE:
                        imageDown6.setBackground(drawable);
                        imageDown6.setVisibility(View.VISIBLE);
                    case Constants.BG_SIX:
                        imageDown7.setBackground(drawable);
                        imageDown7.setVisibility(View.VISIBLE);
                    case Constants.BG_SEVEN:
                        imageDown8.setBackground(drawable);
                        imageDown8.setVisibility(View.VISIBLE);
                    case Constants.BG_EIGHT:
                        imageDown9.setBackground(drawable);
                        imageUp9.setVisibility(View.VISIBLE);
                    case Constants.BG_NINE:
                        imageDown10.setBackground(drawable);
                        imageDown10.setVisibility(View.VISIBLE);
                    case Constants.BG_TEN:

                }
            }
        }



    }

    /**
     * @describetion 獲取條形碼
     * @param
     * @param
     * @return
    */
    private @NonNull Drawable getDrawable(String content) {
        int width = 300; // 条形码的宽度
        int height = 100; // 条形码的高度

        if (barcodes != null && barcodes.size() > 0){

        }
        Bitmap barcodeBitmap = CodeUtils.createBarcode(content, width, height);
        Drawable drawable = new BitmapDrawable(getResources(), barcodeBitmap);
        return drawable;
    }

    /**
     * @describetion gson解析
     * @author mark
     * @param
     * @param
     * @return
    */
    private Barcodes getBarcodes(String jsonStr){
        //List<Barcode> bblist = new ArrayList<>();
        Gson gson = new Gson();
        Barcodes bs =  gson.fromJson(jsonStr, Barcodes.class);
       /* if (bs != null && bs.getVtags() != null){
            bblist = bs.getVtags();
        }*/
        return bs;
    }
    public Point getScreenResolutionWithStatusBar(Activity activity) {
        Point screenResolution = new Point();
        Display display = activity.getWindowManager().getDefaultDisplay();
        display.getRealSize(screenResolution);
        return screenResolution;
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
